const { sequelize } = require('../config/database');
const { Cart, Product, Category } = require('../models');

// 获取购物车
exports.getCart = async (req, res, next) => {
    try {
        const userId = req.user.id;

        const cartItems = await Cart.findAll({
            where: { userId },
            include: [
                {
                    model: Product,
                    as: 'product',
                    attributes: ['id', 'name', 'images', 'stock', 'price', 'isActive'],
                    include: [
                        {
                            model: Category,
                            as: 'category',
                            attributes: ['id', 'name']
                        }
                    ]
                }
            ],
            order: [['createdAt', 'DESC']]
        });

        // 计算购物车统计信息
        let totalItems = 0;
        let totalPrice = 0;
        let validItems = [];

        for (const item of cartItems) {
            // 检查商品是否仍然有效
            if (item.product && item.product.isActive) {
                // 检查库存是否足够
                const availableQuantity = Math.min(item.quantity, item.product.stock);
                
                if (availableQuantity > 0) {
                    // 检查价格是否有变化
                    const currentPrice = parseFloat(item.product.price);
                    const cartPrice = parseFloat(item.unitPrice);
                    
                    const itemData = {
                        ...item.toJSON(),
                        availableQuantity,
                        priceChanged: currentPrice !== cartPrice,
                        currentPrice,
                        subtotal: (currentPrice * availableQuantity).toFixed(2)
                    };

                    validItems.push(itemData);
                    totalItems += availableQuantity;
                    totalPrice += currentPrice * availableQuantity;

                    // 如果数量或价格有变化，更新购物车项
                    if (availableQuantity !== item.quantity || currentPrice !== cartPrice) {
                        await item.update({
                            quantity: availableQuantity,
                            unitPrice: currentPrice
                        });
                    }
                }
            }
        }

        res.json({
            success: true,
            data: {
                cartItems: validItems,
                summary: {
                    totalItems,
                    totalPrice: totalPrice.toFixed(2),
                    itemCount: validItems.length
                }
            }
        });
    } catch (error) {
        next(error);
    }
};

// 添加商品到购物车
exports.addToCart = async (req, res, next) => {
    const transaction = await sequelize.transaction();
    
    try {
        const userId = req.user.id;
        const { productId, quantity = 1 } = req.body;

        // 验证商品是否存在且有效
        const product = await Product.findOne({
            where: { id: productId, isActive: true }
        });

        if (!product) {
            await transaction.rollback();
            return res.status(404).json({
                success: false,
                message: '商品不存在或已下架'
            });
        }

        // 检查库存
        if (product.stock < quantity) {
            await transaction.rollback();
            return res.status(400).json({
                success: false,
                message: `库存不足，当前库存：${product.stock}`
            });
        }

        // 检查是否已在购物车中
        const existingCartItem = await Cart.findOne({
            where: { userId, productId },
            transaction
        });

        if (existingCartItem) {
            // 更新数量
            const newQuantity = existingCartItem.quantity + quantity;
            
            if (product.stock < newQuantity) {
                await transaction.rollback();
                return res.status(400).json({
                    success: false,
                    message: `库存不足，当前库存：${product.stock}，购物车中已有：${existingCartItem.quantity}`
                });
            }

            await existingCartItem.update({
                quantity: newQuantity,
                unitPrice: product.price
            }, { transaction });

            await transaction.commit();

            res.json({
                success: true,
                message: '购物车数量已更新',
                data: { 
                    cartItem: existingCartItem,
                    action: 'updated'
                }
            });
        } else {
            // 创建新的购物车项
            const cartItem = await Cart.create({
                userId,
                productId,
                quantity,
                unitPrice: product.price
            }, { transaction });

            await transaction.commit();

            res.status(201).json({
                success: true,
                message: '商品已添加到购物车',
                data: { 
                    cartItem,
                    action: 'created'
                }
            });
        }
    } catch (error) {
        await transaction.rollback();
        next(error);
    }
};

// 更新购物车商品数量
exports.updateCartItem = async (req, res, next) => {
    try {
        const userId = req.user.id;
        const { id } = req.params;
        const { quantity } = req.body;

        if (quantity < 1) {
            return res.status(400).json({
                success: false,
                message: '数量必须大于0'
            });
        }

        const cartItem = await Cart.findOne({
            where: { id, userId },
            include: [
                {
                    model: Product,
                    as: 'product',
                    attributes: ['id', 'name', 'stock', 'price', 'isActive']
                }
            ]
        });

        if (!cartItem) {
            return res.status(404).json({
                success: false,
                message: '购物车项不存在'
            });
        }

        if (!cartItem.product.isActive) {
            return res.status(400).json({
                success: false,
                message: '商品已下架'
            });
        }

        if (cartItem.product.stock < quantity) {
            return res.status(400).json({
                success: false,
                message: `库存不足，当前库存：${cartItem.product.stock}`
            });
        }

        await cartItem.update({
            quantity,
            unitPrice: cartItem.product.price
        });

        res.json({
            success: true,
            message: '购物车已更新',
            data: { cartItem }
        });
    } catch (error) {
        next(error);
    }
};

// 删除购物车商品
exports.removeFromCart = async (req, res, next) => {
    try {
        const userId = req.user.id;
        const { id } = req.params;

        const deletedRowsCount = await Cart.destroy({
            where: { id, userId }
        });

        if (deletedRowsCount === 0) {
            return res.status(404).json({
                success: false,
                message: '购物车项不存在'
            });
        }

        res.json({
            success: true,
            message: '商品已从购物车移除'
        });
    } catch (error) {
        next(error);
    }
};

// 清空购物车
exports.clearCart = async (req, res, next) => {
    try {
        const userId = req.user.id;

        await Cart.destroy({
            where: { userId }
        });

        res.json({
            success: true,
            message: '购物车已清空'
        });
    } catch (error) {
        next(error);
    }
};

// 批量更新购物车
exports.batchUpdateCart = async (req, res, next) => {
    const transaction = await sequelize.transaction();
    
    try {
        const userId = req.user.id;
        const { items } = req.body; // [{ id, quantity }, ...]

        if (!Array.isArray(items) || items.length === 0) {
            await transaction.rollback();
            return res.status(400).json({
                success: false,
                message: '请提供有效的商品列表'
            });
        }

        const results = [];
        
        for (const item of items) {
            const { id, quantity } = item;
            
            if (quantity < 1) {
                await transaction.rollback();
                return res.status(400).json({
                    success: false,
                    message: `商品ID ${id} 的数量必须大于0`
                });
            }

            const cartItem = await Cart.findOne({
                where: { id, userId },
                include: [
                    {
                        model: Product,
                        as: 'product',
                        attributes: ['id', 'name', 'stock', 'price', 'isActive']
                    }
                ],
                transaction
            });

            if (!cartItem) {
                await transaction.rollback();
                return res.status(404).json({
                    success: false,
                    message: `购物车项 ${id} 不存在`
                });
            }

            if (!cartItem.product.isActive) {
                await transaction.rollback();
                return res.status(400).json({
                    success: false,
                    message: `商品 ${cartItem.product.name} 已下架`
                });
            }

            if (cartItem.product.stock < quantity) {
                await transaction.rollback();
                return res.status(400).json({
                    success: false,
                    message: `商品 ${cartItem.product.name} 库存不足，当前库存：${cartItem.product.stock}`
                });
            }

            await cartItem.update({
                quantity,
                unitPrice: cartItem.product.price
            }, { transaction });

            results.push({
                id: cartItem.id,
                quantity: cartItem.quantity,
                unitPrice: cartItem.unitPrice,
                subtotal: cartItem.getTotalPrice()
            });
        }

        await transaction.commit();

        res.json({
            success: true,
            message: '购物车批量更新成功',
            data: { updatedItems: results }
        });
    } catch (error) {
        await transaction.rollback();
        next(error);
    }
};

// 获取购物车商品数量
exports.getCartCount = async (req, res, next) => {
    try {
        const userId = req.user.id;

        const totalQuantity = await Cart.sum('quantity', {
            where: { userId },
            include: [
                {
                    model: Product,
                    as: 'product',
                    where: { isActive: true },
                    attributes: []
                }
            ]
        });

        res.json({
            success: true,
            data: { 
                count: totalQuantity || 0 
            }
        });
    } catch (error) {
        next(error);
    }
};